/*
    Document   : localStorage
    Created on : 12.04.2013, 14:35:29
    Author     : Eduard S. Markelov
    E-Mail     : MarkelovEduard@gmail.com
    ICQ        : 349127911
    Description:
*/

// https://developer.mozilla.org/en-US/docs/Storage


function UCLocalStorage() {
    var ucLocalStorageDBVer = "1.0";

    this.ucLocalStorageConnection = null;

    Components.utils.import("resource://gre/modules/Services.jsm");
    Components.utils.import("resource://gre/modules/FileUtils.jsm");


    this.CheckDatabaseVersion = function() {
        var result = false;
        var lsc_old = this.ucLocalStorageConnection;

        if ((this.ucLocalStorageConnection !== null) || this.open()) {
            try {
                dbver = this.getItem('DBVer');
            } catch (err) {
                alert(err + '\n\n' + '(Unable to get database version...)');
                return false;
            }
        } else {
            alert('Could not open database...');
            return false;
        }

        if (dbver === ucLocalStorageDBVer) {
            result = true
        } else {
            result = dbver;
        }

        if (lsc_old === null) this.close();

        return result;
    }


    this.open = function() {
        var ucLocalStorageFile = null;
        
        if (this.ucLocalStorageConnection !== null) return true;

        try {
            ucLocalStorageFile = FileUtils.getFile("ProfD", ["unicon.sqlite"]);
        } catch (err) {
            alert(err + '\n\n' + '(Unable to open database file...)');
            return false;
        }

        try {
            this.ucLocalStorageConnection = Services.storage.openDatabase(ucLocalStorageFile);
        } catch (err) {
            alert(err + '\n\n' + '(Unable to create database connection...)');
            return false;
        }

        // проверяю, существует ли таблица в базе
        // её не должно быть, если это первый запуск
        if (!this.ucLocalStorageConnection.tableExists('params') && !this.createParamsTable()) return false;

        // проверяем версию базы данных
        // должна быть равна ucLocalStorageDBVer
        var dbver = this.CheckDatabaseVersion();
        if (dbver !== true) {
            if (dbver !== false) {
                if (confirm('Different database version!\n' + 'Current ver: ' + dbver + '\nRelease ver: ' + ucLocalStorageDBVer + '\nReinitialize database? (Local settings will be erased!)')) {
                    if (!this.createParamsTable()) {
                        alert('Could not create table.');
                        return false;
                    } else return true;
                }
                
                this.close();
                return false;

            } else {
                return false;
            }
        }

        return true;
    }

    this.close = function() {
        try {
            this.ucLocalStorageConnection.close();
        } catch (err) {
            alert(err + '\n\n' + 'An error occured during connection close...');
            return false;
        }

        this.ucLocalStorageConnection = null;

        return true;
    }

    this.setItem = function(iname, ival) {
        try {
            this.ucLocalStorageConnection.executeSimpleSQL('INSERT INTO `params` (`name`, `value`) VALUES (\'' + iname + '\', \'' + ival + '\')');
        } catch (err) {
            // если такая переменная уже существует то надо установить новое значение
            if (this.ucLocalStorageConnection.lastError == 19) {
                try {
                    this.ucLocalStorageConnection.executeSimpleSQL('UPDATE `params` SET `value`=\'' + ival + '\' WHERE `name`=\'' + iname + '\'');
                    return true;
                } catch (err) {
                    alert(err + '\n\n' + '(An error occured during execute UPDATE query...)\n\n' + this.ucLocalStorageConnection.lastError + ':' + this.ucLocalStorageConnection.lastErrorString);
                }
            }
            
            alert(err + '\n\n' + '(An error occured during execute INSERT query...)\n\n' + this.ucLocalStorageConnection.lastError + ':' + this.ucLocalStorageConnection.lastErrorString);
            
            return false;
        }

        return true;
    }
    
    this.getItem = function(iname) {
        var statement = null;
        var result = false;
        
        try {
            statement = this.ucLocalStorageConnection.createStatement('SELECT * FROM `params` WHERE `name`=\'' + iname + '\'');

            if (statement.state == statement.MOZ_STORAGE_STATEMENT_READY) {
                if (statement.step()) {
                    result = statement.row.value;
                } else result = '';
            }
            statement.finalize();
        } catch (err) {
            alert(err + '\n\n' + '(An error occured during execute query...)');
            return false;
        }
        
        return result;
    }

    // создает пустую таблицу в базе
    this.createParamsTable = function() {
        try {
            this.ucLocalStorageConnection.executeSimpleSQL('DROP TABLE IF EXISTS `params`;');
            this.ucLocalStorageConnection.createTable('params', '`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, `name` VARCHAR(255) NOT NULL UNIQUE, `value` VARCHAR(255) NOT NULL DEFAULT \'\'');
            this.setItem('DBVer', ucLocalStorageDBVer);
        } catch (err) {
            alert(err + '\n\n' + 'Could not execute statement...');
            return false;
        }

        return true;
    }
}

